package org.elec.mac.controller;

import javafx.beans.binding.ObjectBinding;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.elec.mac.constants.Constants;
import org.elec.mac.entity.*;
import org.elec.mac.service.*;
import org.elec.mac.utils.JSONUtil;
import org.elec.mac.utils.Maxcup;
import org.elec.mac.utils.PriceUtil;
import org.elec.mac.utils.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * Created by Bean on 2018/4/2.
 */
@Slf4j
@Controller
public class MachineDetailController extends BaseController {

    @Autowired
    private SMachineService sMachineService;

    @Autowired
    private SDeviceService sDeviceService;

    @Autowired
    private SMachineTechService sMachineTechService;

    @Autowired
    private SMachineMenuService sMachineMenuService;

    @Autowired
    private SMachineMaterialService sMachineMaterialService;

    @Autowired
    private SProductService sProductService;

    @Autowired
    private SFormulaService sFormulaService;

    @Autowired
    private SMateLogService sMateLogService;

    //机台明细
    @RequestMapping("/machine_detail.do")
    public String machineDetailHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model,
                                       @RequestParam(value = "action", required = false, defaultValue = "") String action,
                                       @RequestParam(value = "id", required = false, defaultValue = "") String id) throws IOException {
        Map<String, Object> param = new HashMap<>();
        Long mid = Utils.parseLong(id, 0L);
        param.put("id", mid);
        //机台查询
        SMachine sMachine = sMachineService.get(param);
        param.clear();
        param.put("id", sMachine.getDid());
        //设备查询
        SDevice sDevice = sDeviceService.get(param);
        param.clear();
        param.put("machid", Utils.parseLong(id, 0L));
        //参数数据查询
        List<Map<String, Object>> sMachineTechList = sMachineTechService.getMachineTechList(param);
        //机台菜单查询(关联)
        List<Map<String, Object>> sMachineMenuList = sMachineMenuService.getMachineMenuList(param);
        //机台原料查询（关联）
        param.put("sign", 0);
        List<Map<String, Object>> sMachineMaterialList = sMachineMaterialService.getMachineMaterialList(param);
       //机台基础配方（关联）
        param.put("sign", 1);
        List<Map<String, Object>> sMachineBasicslList = sMachineMaterialService.getMachineMaterialList(param);
        model.put("sMachine", sMachine);
        model.put("sDevice", sDevice);
        model.put("sMachineTechList", sMachineTechList);
        model.put("sMachineMenuList", sMachineMenuList);
        model.put("machineMaterialList", sMachineMaterialList);
        model.put("machineBasicsList", sMachineBasicslList);
        model.put("machid", id);
        return "/machine/machine_detail";
    }

    //机台菜单新增
    @RequestMapping(value = "/machinemenu_add.do")
    public void machineMenuAddHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model,
                                      @RequestParam(value = "action", required = false, defaultValue = "") String action) throws IOException {
        ExecuteResult result = new ExecuteResult();
        result.setSuccess(true);
        result.setMsg("成功");
        Long machid = Utils.parseLong(this.getParameter(request, "machid"), 0L);
        if("do".equals(action)) {
            try {
                Long pid = Utils.parseLong(this.getParameter(request, "pid"), 0L);
                String cprice = this.getParameter(request, "cprice");
                //原料id列表
                Map<String, Object> params = new HashMap<>();
                params.put("pid", pid);
                // 产品配方下的物料
                List<Long> sMaterialList = sFormulaService.getFormulaMaterialList(params);

                //待新增产品原料
                List<SFormula> sFormulaList = sFormulaService.list(params);
                //机台的原料
                params.put("machid", machid);
                List<SMachineMaterial> sMachineMaterialList = sMachineMaterialService.list(params);

                Integer maxcup = Maxcup.result(sFormulaList, sMachineMaterialList);

                if(sMaterialList == null || sMaterialList.size() <= 0) {
                    result.setSuccess(false);
                    result.setMsg("原料添加不成功");
                }
                if(result.isSuccess() && machid == 0L) {
                    result.setSuccess(false);
                    result.setMsg("机台不能为空");
                }
                if(result.isSuccess() && pid == 0L) {
                    result.setSuccess(false);
                    result.setMsg("产品不能为空");
                }
                if(result.isSuccess() && StringUtils.isBlank(cprice)) {
                    result.setSuccess(false);
                    result.setMsg("当前价不能为空");
                }
                if(result.isSuccess()) {
                    SMachineMenu sMachineMenu = new SMachineMenu();
                    sMachineMenu.setMachid(machid);
                    sMachineMenu.setPid(pid);
                    sMachineMenu.setCprice(PriceUtil.parse(cprice));
                    sMachineMenu.setMaxcup(maxcup);
                    sMachineMenuService.insert(sMachineMenu);
                    log.info("机台菜单新增");
                }
            } catch(Exception ex) {
                log.error("机台菜单新增错误", ex);
                result.setSuccess(false);
                result.setMsg("机台菜单新增错误");
            }
        } else {
            Map<String, Object> param = new HashMap<>();
            param.put("machid", machid);
            List<SProduct> sProductList = sProductService.getOtherProductList(param);
            List<SMachineMaterial> machineMaterialList = sMachineMaterialService.list(param);

            StringBuilder builder = new StringBuilder();

            if(sProductList != null && sProductList.size() > 0) {
                builder.append("<option value=\"\">---请选择---</option>");
                int count = 0;
                for(int i = 0; i < sProductList.size(); i++) {
                    boolean flag = false;
                    //获取产品的所有原料
                    List<Map<String, Object>> productMaterial = sProductService.getProductMaterial(sProductList.get(i).getId());
                    for (int j = 0; j < productMaterial.size(); j++) {
                        for (SMachineMaterial item : machineMaterialList) {
                            if(item.getMid().equals(productMaterial.get(j).get("maid"))) {
                                flag = true;
                                count++;
                                break;
                            } else {
                                flag = false;
                            }
                        }
                    }

                    if(flag && count == productMaterial.size()) {
                        builder.append("<option value=\"" + sProductList.get(i).getId() + "\">");
                        builder.append(sProductList.get(i).getName() + " 原价:" + PriceUtil.toPriceString(sProductList.get(i).getPrice()));
                        builder.append("</option>");
                    }
                    count = 0;
                }
            }
            result.getBody().put("sProductList", builder.toString());
        }

        log.info(JSONUtil.object2json(result));
        response.getWriter().write(JSONUtil.object2json(result));
    }


    //机台菜单修改
    @RequestMapping(value = "/machinemenu_edit.do")
    public void machineMenuEditHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model,
                                       @RequestParam(value = "action", required = false, defaultValue = "") String action,
                                       @RequestParam(value = "id", required = false, defaultValue = "") String id) throws IOException {
        ExecuteResult result = new ExecuteResult();
        result.setSuccess(true);
        result.setMsg("成功");
        if("edit".equals(action)) {
            try {
                Map<String, Object> params = new HashMap<>();
                params.put("id", Utils.parseLong(id, 0L));
                SMachineMenu sMachineMenu = sMachineMenuService.get(params);
                result.getBody().put("sMachineMenu", sMachineMenu);
                log.info("机台菜单修改开启");
            } catch(Exception ex) {
                log.error("机台菜单修改开启错误", ex);
                result.setSuccess(false);
                result.setMsg("机台菜单修改开启错误");
            }
        }
        if("doEdit".equals(action)) {
            try {
                Long machinemenuid = Utils.parseLong(this.getParameter(request, "machinemenuid"), 0L);
                String cprice = this.getParameter(request, "cprice");
                if(machinemenuid == 0L) {
                    result.setSuccess(false);
                    result.setMsg("菜单不能为空");
                }
                if(StringUtils.isBlank(cprice)) {
                    result.setSuccess(false);
                    result.setMsg("当前价不能为空");
                }
                if(result.isSuccess()) {
                    SMachineMenu sMachineMenu = new SMachineMenu();
                    sMachineMenu.setId(machinemenuid);
                    sMachineMenu.setCprice(PriceUtil.parse(cprice));
                    sMachineMenuService.update(sMachineMenu);
                    log.info("机台菜单修改");
                }
            } catch(Exception ex) {
                log.error("机台菜单修改错误", ex);
                result.setSuccess(false);
                result.setMsg("机台菜单修改错误");
            }
        }
        if("doDelete".equals(action)) {
            try {
                Map<String, Object> params = new HashMap<>();
                Long pid = Utils.parseLong(this.getParameter(request, "pid"), 0L);
                Long machid = Utils.parseLong(this.getParameter(request, "machid"), 0L);
                if(StringUtils.isBlank(id)) {
                    result.setSuccess(false);
                    result.setMsg("机台名不能为空");
                }
                if(result.isSuccess() && pid == 0L) {
                    result.setSuccess(false);
                    result.setMsg("产品不能为空");
                }
                if(result.isSuccess() && machid == 0L) {
                    result.setSuccess(false);
                    result.setMsg("机台不能为空");
                }
                params.put("pid", pid);
                // 产品配方下的物料
                List<Long> sMaterialList = sFormulaService.getFormulaMaterialList(params);
                // 机台其他产品所需要的物料
                params.put("machid", machid);
                List<Long> list = sMachineMenuService.getOtherMaterialIDList(params);
                // 机台新增原料(如果原料已经存在不再重复增加)
                List<Long> poList = new ArrayList<>();
                for(int i = 0; i < sMaterialList.size(); i++) {
                    if(!list.contains(sMaterialList.get(i))) {
                        poList.add(sMaterialList.get(i));
                    }
                }
                params.clear();
                params.put("id", Utils.parseLong(id, 0L));
                sMachineMenuService.delete(params);
                log.info("机台菜单删除");
                // 删除机台原料
//                sMachineMaterialService.deleteMachineMaterial(machid, poList);
//                log.info("机台原料删除");
            } catch(Exception ex) {
                log.error("机台菜单删除错误", ex);
                result.setSuccess(false);
                result.setMsg("机台菜单删除错误");
            }
        }
        log.info(JSONUtil.object2json(result));
        response.getWriter().write(JSONUtil.object2json(result));
    }

    //机台原料修改
    @RequestMapping(value = "/machinematerial_edit.do")
    public void machineMaterialEditHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model,
                                           @RequestParam(value = "action", required = false, defaultValue = "") String action,
                                           @RequestParam(value = "id", required = false, defaultValue = "") String id) throws IOException {
        ExecuteResult result = new ExecuteResult();
        result.setSuccess(true);
        result.setMsg("成功");

        if("edit".equals(action)) {
            try {
                Map<String, Object> params = new HashMap<>();
                params.put("id", Utils.parseLong(id, 0L));
                SMachineMaterial sMachineMaterial = sMachineMaterialService.get(params);
                result.getBody().put("sMachineMaterial", sMachineMaterial);
                log.info("机台原料修改开启");
            } catch(Exception ex) {
                log.error("机台原料修改开启错误", ex);
                result.setSuccess(false);
                result.setMsg("机台原料修改开启错误");
            }
        }
        if("doEdit".equals(action)) {
            try {
                Long machinematerialid = Utils.parseLong(this.getParameter(request, "machinematerialid"), 0L);
                Integer warning = Utils.parseInt(this.getParameter(request, "warning"), Constants.UnknowInteger);
                Integer amount = Utils.parseInt(this.getParameter(request, "amount"), Constants.UnknowInteger);
                if(machinematerialid == 0L) {
                    result.setSuccess(false);
                    result.setMsg("原料不能为空");
                }
                if(result.isSuccess() && warning == 0) {
                    result.setSuccess(false);
                    result.setMsg("警告值不能为空");
                }
                if(result.isSuccess() && amount == 0) {
                    result.setSuccess(false);
                    result.setMsg("当前数不能为空");
                }
                if(result.isSuccess()) {
                    SMachineMaterial sMachineMaterial = new SMachineMaterial();
                    sMachineMaterial.setId(machinematerialid);
                    sMachineMaterial.setWarning(warning);
                    sMachineMaterial.setAmount(amount);
                    sMachineMaterialService.update(sMachineMaterial);
                    log.info("机台原料修改");
                    Map<String, Object> params = new HashMap<>();
                    params.put("id", machinematerialid);
                    SMachineMaterial material = sMachineMaterialService.get(params);

                    //更新并重新计算机台菜单中的产品库存
                    params.clear();
                    params.put("machid", material.getMachid());
                    List<SMachineMaterial> sMachineMaterialList = sMachineMaterialService.list(params);
                    List<SMachineMenu> menuList = sMachineMenuService.list(params);
                    if(sMachineMaterialList != null && sMachineMaterialList.size() > 0
                            && menuList != null && menuList.size() > 0) {
                        for (SMachineMenu item : menuList) {
                            params.clear();
                            params.put("pid", item.getPid());
                            List<SFormula> sFormulaList = sFormulaService.list(params);
                            item.setMaxcup(Maxcup.result(sFormulaList, sMachineMaterialList));
                            sMachineMenuService.update(item);
                        }
                    }


                    //记录修改的日志
                    SMateLog sMateLog = new SMateLog();
                    sMateLog.setOperid(getSessionUsername(request));
                    sMateLog.setMid(material.getMid());
                    sMateLog.setAmount(material.getAmount());
                    sMateLog.setMachid(material.getMachid());
                    sMateLog.setCreateTime(new Date());
                    sMateLogService.insert(sMateLog);
                }
            } catch(Exception ex) {
                log.error("机台原料修改错误", ex);
                result.setSuccess(false);
                result.setMsg("机台原料修改错误");
            }
        }
        log.info(JSONUtil.object2json(result));
        response.getWriter().write(JSONUtil.object2json(result));
    }
}
